from datetime import datetime
from sqlalchemy import Column, Integer, String, DateTime, JSON, ForeignKey, Float
from sqlalchemy.orm import relationship
from ..database import Base

# 数据库模型
class Process(Base):
    __tablename__ = "processes"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(50), nullable=False)
    description = Column(String)
    status = Column(String(20), default="stopped")  # stopped, running, error
    created_at = Column(DateTime, default=datetime.now)
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
    user_id = Column(Integer, ForeignKey("users.id"))

    user = relationship("User", back_populates="processes")
    versions = relationship("ProcessVersion", back_populates="process")
    nodes = relationship("ProcessNode", back_populates="process")
    edges = relationship("ProcessEdge", back_populates="process")

class ProcessVersion(Base):
    __tablename__ = "process_versions"

    id = Column(Integer, primary_key=True, index=True)
    process_id = Column(Integer, ForeignKey("processes.id"))
    version_number = Column(String(20), nullable=False)
    data = Column(JSON, nullable=False)
    created_at = Column(DateTime, default=datetime.now)
    comment = Column(String)

    process = relationship("Process", back_populates="versions")

class ProcessNode(Base):
    __tablename__ = "process_nodes"

    id = Column(Integer, primary_key=True, index=True)
    process_id = Column(Integer, ForeignKey("processes.id"))
    node_type = Column(String(50), ForeignKey("node_types.type"))
    label = Column(String(100))
    properties = Column(JSON)
    position_x = Column(Float)
    position_y = Column(Float)

    process = relationship("Process", back_populates="nodes")
    type_info = relationship("NodeType")
    outgoing_edges = relationship("ProcessEdge", foreign_keys="ProcessEdge.source_node_id", back_populates="source_node")
    incoming_edges = relationship("ProcessEdge", foreign_keys="ProcessEdge.target_node_id", back_populates="target_node")

class ProcessEdge(Base):
    __tablename__ = "process_edges"

    id = Column(Integer, primary_key=True, index=True)
    process_id = Column(Integer, ForeignKey("processes.id"))
    source_node_id = Column(Integer, ForeignKey("process_nodes.id"))
    target_node_id = Column(Integer, ForeignKey("process_nodes.id"))
    properties = Column(JSON)

    process = relationship("Process", back_populates="edges")
    source_node = relationship("ProcessNode", foreign_keys=[source_node_id], back_populates="outgoing_edges")
    target_node = relationship("ProcessNode", foreign_keys=[target_node_id], back_populates="incoming_edges")

class NodeType(Base):
    __tablename__ = "node_types"

    type = Column(String(50), primary_key=True)
    label = Column(String(100), nullable=False)
    default_properties = Column(JSON)
    icon = Column(String(50))
    category = Column(String(50)) 